import store from "@/store"

let indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
let openRequest = indexedDB.open("aiet", 1) || indow.mozIndexedDB();
let db;

export function dbInit(){
    openRequest.onsuccess = function (e) {
        db = e.target.result
        console.log("数据打开成功=>", db)
    };
        
    openRequest.onerror = function (e) {
        console.log("数据打开失败=>", e)
    };

    openRequest.onupgradeneeded = function (event) {
        console.log("数据库创建或者升级的时候触发")
        db = event.target.result;
        let objectStore;
        // 注册表
        if (!db.objectStoreNames.contains("chat")) {
            objectStore = db.createObjectStore("chat", { keyPath: 'id', autoIncrement: true });
            objectStore.createIndex('userId', 'userId', { unique: true })
            objectStore.createIndex('createTime', 'createTime', { unique: false })
        }
    };
}

export function insetFun(storeName, data){
    return new Promise((resolve, reject) => {
        let request = db.transaction([storeName], 'readwrite').objectStore(storeName).add(data)
        request.onsuccess = function(event) {
            resolve(event)
            console.log("插入成功")
        }
        request.onerror = function(event) {
            // console.log(event.target.error)
            // console.log(event.target.error.message.includes("Unable to add key to index 'userId'") || event.target.error.message..includes("Key already exists in the object store"))
            // if(event.target.error.message.includes("Unable to add key to index 'userId'") || event.target.error.message.includes("Key already exists in the object store")) {
                let selectRequest = db.transaction([storeName], 'readwrite').objectStore(storeName).index("userId").openCursor(null, 'prev')
                console.log(selectRequest)
                selectRequest.onsuccess = function(res){
                    console.log(res.target.result.value.id)
                    updateFun(storeName, data, res.target.result.value.id)
                }  
            // }
        }
    })
}

export function selectFun(storeName, wId){
    return new Promise((resolve, reject) => {
        let request = db.transaction([storeName], 'readwrite').objectStore(storeName).index("createTime").openCursor(null, 'prev')
        let list = []
        request.onsuccess = function(event) {
            let result = event.target.result
            if(result) {
                list.push(result.value)
                result.continue();
            }
            resolve(list)
        }
        request.onerror = function(event) {
            console.log("获取失败")
        }
    })
}

export function updateFun(storeName, data, id){
    return new Promise((resolve, reject) => {
        let objectStore = db.transaction([storeName], 'readwrite').objectStore(storeName)
        let newDate = data
        newDate.id = id
        let request = objectStore.put(newDate)
        request.onsuccess = function(event) {
            resolve(event)
            console.log("更新成功")
            store.state.messageRandom = Math.random()
        }
        request.onerror = function(event) {
            console.log("更新失败", event)
        }
    })
}

